package com.siruier.boss.ui.utils

//import com.yanzhenjie.album.AlbumFile
//import com.yanzhenjie.album.AlbumLoader
import android.app.Activity
import android.app.Fragment
import android.content.Context
import android.graphics.Bitmap
import android.graphics.PointF
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.ImageView
import androidx.annotation.Nullable
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import androidx.fragment.app.FragmentActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.BitmapImageViewTarget
import com.bumptech.glide.request.target.ImageViewTarget
import com.luck.picture.lib.engine.ImageEngine
import com.luck.picture.lib.listener.OnImageCompleteCallback
import com.luck.picture.lib.tools.MediaUtils
import com.luck.picture.lib.widget.longimage.ImageSource
import com.luck.picture.lib.widget.longimage.ImageViewState
import com.luck.picture.lib.widget.longimage.SubsamplingScaleImageView
import com.siruier.boss.ui.R
import com.siruier.boss.ui.ext.dp
import jp.wasabeef.glide.transformations.RoundedCornersTransformation


object GlideUtils {
    /**
     * 加载圆形
     */
    fun intoCircle(tag: Any, url: Any?, imageView: ImageView, placeholder: Int? = null) {
        if (url == null) return
        withRequestManager(tag)?.run {
            val requestBuilder = load(url)
            if (placeholder != null) requestBuilder.placeholder(placeholder).error(placeholder)
            requestBuilder.apply(RequestOptions.circleCropTransform())
            requestBuilder.into(imageView)
        }
    }
    // Glide.with(ivImage.context).load(bean.filePath ?: bean.url ?: bean.resId).apply(RequestOptions().transform(CenterCrop(), RoundedCorners(SizeUtils.dp2px(10f)))).into(ivImage)
    /**
     * 加载圆角
     */
    fun intoRoundedCorners(
        tag: Any,
        url: Any?,
        imageView: ImageView,
        placeholder: Int? = null,
        roundingRadius: Int? = null
    ) {
        if (url == null) return
        withRequestManager(tag)?.run {
            val requestBuilder = load(url)
            if (placeholder != null) requestBuilder.placeholder(placeholder).error(placeholder)
            if (roundingRadius != null) requestBuilder.apply(
                RequestOptions().transform(
                    CenterCrop(),
                    RoundedCorners(roundingRadius.dp)
                )
            )
            requestBuilder.into(imageView)
        }
    }

    /**
     * 加载圆角,设置那个方向需要圆角
     */
    fun intoRoundedCorners(
        tag: Any,
        url: Any?,
        imageView: ImageView,
        placeholder: Int? = null,
        roundingRadius: Int? = 0,
        cornerType: RoundedCornersTransformation.CornerType
    ) {
        if (url == null) return
        withRequestManager(tag)?.run {
            val requestBuilder = load(url)
            if (placeholder != null) requestBuilder.placeholder(placeholder).error(placeholder)
            if (roundingRadius != null) requestBuilder.apply(
                RequestOptions().transform(
                    CenterCrop(),
                    RoundedCornersTransformation(roundingRadius.dp, 0, cornerType)
                )
            )
            requestBuilder.into(imageView)
        }
    }

    fun intoView(
        tag: Any,
        url: Any?,
        imageView: ImageView,
        requestOptions: RequestOptions? = null,
        placeholder: Int? = null,
        error: Int? = null
    ) {
        if (url == null) return
        withRequestManager(tag)?.run {
            val requestBuilder = load(url)
            if (requestOptions != null)
                requestBuilder.apply(requestOptions)
            if (placeholder != null) requestBuilder.placeholder(placeholder)
            if (error != null) requestBuilder.error(error)
            requestBuilder.into(imageView)
        }
    }

    private fun withRequestManager(tag: Any): RequestManager? {
        return when (tag) {
            is View -> Glide.with(tag)
            is Context -> Glide.with(tag)
            is Activity -> Glide.with(tag)
            is androidx.fragment.app.Fragment -> Glide.with(tag)
            is FragmentActivity -> Glide.with(tag)
            is Fragment -> Glide.with(tag)
            else -> {
                Logger.e("tag不合法")
                null
            }
        }

    }
}

//class GlideAlbumLoader : AlbumLoader {
//    override fun load(imageView: ImageView, albumFile: AlbumFile) {
//        load(imageView, albumFile.path)
//    }
//
//    override fun load(imageView: ImageView, imagePath: String) {
//        Glide.with(imageView.context)
//            .load(imagePath)
//            .into(imageView)
//    }
//}

class GlideEngine private constructor() : ImageEngine {
    /**
     * 加载图片
     *
     * @param context
     * @param url
     * @param imageView
     */
    override fun loadImage(context: Context, url: String, imageView: ImageView) {
        Glide.with(context)
            .load(url)
            .into(imageView)
    }

    /**
     * 加载网络图片适配长图方案
     * # 注意：此方法只有加载网络图片才会回调
     *
     * @param context
     * @param url
     * @param imageView
     * @param longImageView
     * @param callback      网络图片加载回调监听 {link after version 2.5.1 Please use the #OnImageCompleteCallback#}
     */
    override fun loadImage(
        context: Context, url: String,
        imageView: ImageView,
        longImageView: SubsamplingScaleImageView, callback: OnImageCompleteCallback
    ) {
        Glide.with(context)
            .asBitmap()
            .load(url)
            .into(object : ImageViewTarget<Bitmap?>(imageView) {
                override fun onLoadStarted(@Nullable placeholder: Drawable?) {
                    super.onLoadStarted(placeholder)
                    if (callback != null) {
                        callback.onShowLoading()
                    }
                }

                override fun onLoadFailed(@Nullable errorDrawable: Drawable?) {
                    super.onLoadFailed(errorDrawable)
                    if (callback != null) {
                        callback.onHideLoading()
                    }
                }

                override fun setResource(@Nullable resource: Bitmap?) {
                    if (callback != null) {
                        callback.onHideLoading()
                    }
                    if (resource != null) {
                        val eqLongImage: Boolean = MediaUtils.isLongImg(
                            resource.width,
                            resource.height
                        )
                        longImageView.visibility = if (eqLongImage) View.VISIBLE else View.GONE
                        imageView.visibility = if (eqLongImage) View.GONE else View.VISIBLE
                        if (eqLongImage) {
                            // 加载长图
                            longImageView.isQuickScaleEnabled = true
                            longImageView.isZoomEnabled = true
                            longImageView.setDoubleTapZoomDuration(100)
                            longImageView.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CENTER_CROP)
                            longImageView.setDoubleTapZoomDpi(SubsamplingScaleImageView.ZOOM_FOCUS_CENTER)
                            longImageView.setImage(
                                ImageSource.bitmap(resource),
                                ImageViewState(0f, PointF(0f, 0f), 0)
                            )
                        } else {
                            // 普通图片
                            imageView.setImageBitmap(resource)
                        }
                    }
                }
            })
    }

    /**
     * 加载相册目录
     *
     * @param context   上下文
     * @param url       图片路径
     * @param imageView 承载图片ImageView
     */
    override fun loadFolderImage(context: Context, url: String, imageView: ImageView) {
        Glide.with(context)
            .asBitmap()
            .load(url)
            .override(180, 180)
            .centerCrop()
            .sizeMultiplier(0.5f)
            .apply(RequestOptions().placeholder(R.drawable.picture_image_placeholder))
            .into(object : BitmapImageViewTarget(imageView) {
                override fun setResource(resource: Bitmap?) {
                    val circularBitmapDrawable =
                        RoundedBitmapDrawableFactory.create(context.resources, resource)
                    circularBitmapDrawable.cornerRadius = 8f
                    imageView.setImageDrawable(circularBitmapDrawable)
                }
            })
    }

    /**
     * 加载图片列表图片
     *
     * @param context   上下文
     * @param url       图片路径
     * @param imageView 承载图片ImageView
     */
    override fun loadGridImage(context: Context, url: String, imageView: ImageView) {
        Glide.with(context)
            .load(url)
            .override(200, 200)
            .centerCrop()
            .apply(RequestOptions().placeholder(R.drawable.picture_image_placeholder))
            .into(imageView)
    }

    companion object {
        private var instance: GlideEngine? = null
        fun createGlideEngine(): GlideEngine? {
            if (null == instance) {
                synchronized(GlideEngine::class.java) {
                    if (null == instance) {
                        instance = GlideEngine()
                    }
                }
            }
            return instance
        }
    }
}